package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.dto.PaAgentDto;
import cn.chinaflame.pagodas.entity.PaAgent;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaAgentRepository;
import cn.chinaflame.pagodas.req.PaAgentReq;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.Digests;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author created by lbq
 * @date 2018年1月4日 下午2:50:01
 **/
@Service
public class LoginService {
    private final static Logger log = LoggerFactory.getLogger(LoginService.class);
    @Autowired
    private PaAgentRepository ywAgentRepository;

    /**
     * 代理登录
     */
    public PaAgentDto login(String phone, String password) {
        log.info("登录手机号phone:{},密码password:{}", phone, password);
        ParamPreconditions.checkNotEmpty(phone, CodeEnum.FAIL.getCode(), "手机号不能为空");
        ParamPreconditions.checkNotEmpty(password, CodeEnum.FAIL.getCode(), "密码不能为空");
        PaAgent ywAgent = ywAgentRepository.findOne(phone);
        ParamPreconditions.checkArgument(!Objects.isNull(ywAgent), CodeEnum.FAIL.getCode(), "用户不存在");
        String mima = Digests.md5DigestAsHex(password);
        ParamPreconditions.checkArgument(mima.equals(ywAgent.getLoginPwd()), CodeEnum.FAIL.getCode(), "账号密码错误");
        PaAgentDto dto = new PaAgentDto();
        BeanUtils.copyProperties(ywAgent, dto);
        return dto;
    }

    /**
     * 代理注册添加
     */
    public PaAgentDto registe(PaAgentReq agentReq) {
        agentReq.check();
        agentReq.setLoginPwd("123456");//设置初始密码
        agentReq.setLoginId("123");
        PaAgent agent = new PaAgent();

        PaAgent ywAgent = ywAgentRepository.findOne(agentReq.getMobile());
        ParamPreconditions.checkArgument(Objects.isNull(ywAgent), CodeEnum.FAIL.getCode(), "用户已存在");
        BeanUtils.copyProperties(agentReq, agent);
        agent.setCreatetime(DateTimes.nowDateTime());
        agent.setUpdatetime(DateTimes.nowDateTime());
        agent.setId("11112222");
        agent = ywAgentRepository.save(agent);
        PaAgentDto dto = new PaAgentDto();
        BeanUtils.copyProperties(agent, dto);
        return dto;
    }
}
